const express = require('express');
const axios = require('axios');
const app = express();
const port = 3000;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

class NoteGenerator {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.baseUrl = "https://openrouter.ai/api/v1/chat/completions";
  }

  async generateNote(prompt, model = "deepseek/deepseek-chat-v3.1:free") {
    try {
      const response = await axios.post(this.baseUrl, {
        model: model,
        messages: [
          {
            role: "user",
            content: `请根据以下内容生成结构化的笔记：\n${prompt}`
          }
        ]
      }, {
        headers: {
          "Authorization": `Bearer ${this.apiKey}`,
          "Content-Type": "application/json"
        }
      });

      return response.data.choices[0].message.content;
    } catch (error) {
      console.error("生成笔记时出错:", error);
      throw error;
    }
  }
}

const noteGenerator = new NoteGenerator("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");

// 主页路由
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// API路由
app.post('/generate-note', async (req, res) => {
  try {
    const note = await noteGenerator.generateNote(req.body.prompt);
    res.json({ note });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

app.listen(port, () => {
  console.log(`服务器运行在 http://localhost:${port}`);
});

// 生成笔记示例
noteGenerator.generateNote("量子力学的基本原理")
    .then(note => console.log("生成的笔记:\n", note))
    .catch(err => console.error(err));